import { API_RESULT } from "../constants/api"
import { API_ENDPOINTS, buildUrl, RET_CODE } from "./endpoints"
import service from "./service"

export async function get_factories() {
    try {
        const { data } = await service.get(buildUrl('llm', API_ENDPOINTS.llm.factories))
        if (data.code != RET_CODE.SUCCESS) {
            console.warn(`get_factories failed, code: ${data.code}, msg: ${data.message}`)
        }
        return data?.data ?? []
    } catch (error) {
        console.error('get_factories error:', error)
        return []
    }
}

export function tenant_llm_name(llm) {
    return `${llm.llm_factory}@${llm.llm.llm_name}`
}

export async function set_tenant_llm(data) {
    const body = {}
    body.llm_factory = data.llm_factory
    body.llm_name = data.llm.llm_name
    body.name = tenant_llm_name(data)
    body.model_type = data.llm.model_type
    body.api_key = data.api_key
    body.max_tokens = data.llm.max_tokens
    body.llm_setting = {}
    Object.entries(data.fieldSwitches).forEach(([key, value]) => {
        if (value) {
            body.llm_setting[key] = data.llm_setting[key]
        }
    })
    try {
        const { data } = await service.post(buildUrl('llm', API_ENDPOINTS.llm.set_tenant_llm), body)
        if (data.code != RET_CODE.SUCCESS) {
            console.warn(`set_tenant_llm failed, code: ${data.code}, msg: ${data.message}`)
            return API_RESULT.FAILED
        }
        return API_RESULT.SUCCESS
    } catch (error) {
        console.error('set_tenant_llm error:', error)
        return API_RESULT.FAILED
    }
}

export async function tenant_llm_list() {
    try {
        const { data } = await service.get(buildUrl('llm', API_ENDPOINTS.llm.tenant_llm_list))
        if (data.code != RET_CODE.SUCCESS) {
            console.warn(`tenant_llm_list failed, code: ${data.code}, msg: ${data.message}`)
        }
        return data?.data ?? []
    } catch (error) {
        console.error('tenant_llm_list error:', error)
        return []
    }
}